﻿using System;
using System.Web;
using System.Web.SessionState;
using CommonUtility.Utility;

namespace UIDevCore
{
    public class PostHttpHandler : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            PostData postData = UIHelper.GetPostData(context);
            string responseData = null;
            UIEmnus.EError errType = UIEmnus.EError.NoError;
            if (postData != null && !string.IsNullOrEmpty(postData.No))
            {
                FnCode fncode = new FnCode(postData.No);
                if (fncode.HasValue)
                {
                    errType = fncode.CheckRight();
                    if (errType == UIEmnus.EError.NoError)
                    {
                        string error = null;
                        //try
                        //{
                        object data = GetResponseData(postData, fncode, ref error);
                        if (data != null)
                            responseData = UIHelper.GetResponseData(data, error);
                        //}
                        //catch (Exception ex)
                        //{
                        //    responseData = JsonHelper.SerializeData(new ResponseData() { Error= ex.Message});
                        //}
                    }
                    else
                        responseData = UIHelper.GetErrorResponseData(errType);
                }
                else
                    errType = UIEmnus.EError.NoFunction;
            }
            if (responseData == null)
                responseData = UIHelper.GetErrorResponseData(errType == UIEmnus.EError.NoError ? UIEmnus.EError.Request : errType);
            context.Response.ContentType = UIConst.ContentType_Json;
            context.Response.Write(responseData);
        }

        protected virtual object GetResponseData(PostData postData,FnCode fncode, ref string error)
        {
            return null;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}